package com.itmuch.box.service.category;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itmuch.box.core.base.BaseService;
import com.itmuch.box.core.constant.ConstantCode;
import com.itmuch.box.core.converter.AjaxResult;
import com.itmuch.box.dao.category.CategoryRepository;
import com.itmuch.box.dao.content.ContentRepository;
import com.itmuch.box.domain.category.entity.Category;
import com.itmuch.box.util.ErrorMsgUtil;

@Service
@Transactional
public class CategoryService extends BaseService<CategoryRepository, Category> {
    @Autowired
    private ContentRepository contentRepository;

    public AjaxResult deleteById4Res(Integer id) {
        Long countByParentId = this.dao.countByParentId(id);
        // 栏目无子栏目
        if (countByParentId == 0) {
            Long contentCount = this.contentRepository.countByCategoryId(id);
            // 栏目下无内容, 允许删除
            if (contentCount == 0) {
                this.dao.delete(id);
                return new AjaxResult("成功.", "栏目删除成功.");
            }
            // 栏目下有内容
            else {
                return ErrorMsgUtil.error("错误.", "所选栏目下有内容, 请先删除栏目下的内容.", ConstantCode.PARAMTER_ERROR_CODE);
            }
        }
        // 栏目有子栏目
        else {
            return ErrorMsgUtil.error("错误.", "所选栏目有子栏目, 请先删除子栏目.", ConstantCode.PARAMTER_ERROR_CODE);
        }
    }

    public Set<Category> findByModelId(Integer modelId) {
        return this.dao.findByModelId(modelId);
    }
}
